package com.base.cn.platform.os.service.manage.work;

import com.base.cn.platform.os.common.exception.BaseException;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.manage.work.SysWorkBlockSortDao;
import com.base.cn.platform.os.entity.manage.work.SysWorkBlockSort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工作台排序Biz
 *
 * @author s.li
 * @create 2018-04-16-8:50
 */
@Service
public class SysWorkBlockSortBiz extends BaseBiz<SysWorkBlockSort,SysWorkBlockSortDao> {

    /**
     * 保存工作台权限排序
     * @param userId
     * @param sysWorkBlockSortList
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void saveSysWorkBlockSort(BigDecimal userId, List<SysWorkBlockSort> sysWorkBlockSortList){
        List<SysWorkBlockSort> workBlockSortList = this.findSysWorkBlockSortByUserId(userId);
        if(ObjectUtils.isNotEmpty(workBlockSortList) && sysWorkBlockSortList.size()==workBlockSortList.size()){//修改
            Map<String,SysWorkBlockSort> sysWorkBlockSortMap = sysWorkBlockSortList.stream().collect(Collectors.toMap(e->e.getBlockKey(),e->e));
            workBlockSortList.forEach(e->{
                SysWorkBlockSort sort = sysWorkBlockSortMap.get(e.getBlockKey());
                if(sort==null){
                    throw new BaseException("工作台数据错误");
                }
                //修改排序值
                e.setSort(sort.getSort());
            });
            this.updateBatch(workBlockSortList);
        }else{//添加
            this.deleteWhereSql(" userId="+userId);
            sysWorkBlockSortList.forEach(e->{
                e.setUserId(userId);//设置用户ID
            });
            this.batchSave(sysWorkBlockSortList);
        }
    }

    /**
     * 通过用户ID查询用户的工作台权限块排序
     * @param userId　用户ID
     * @return  List<SysWorkBlockSort>
     */
    public List<SysWorkBlockSort> findSysWorkBlockSortByUserId(BigDecimal userId){
        return this.find("userId="+userId,null,null);
    }
}
